package com.niguang.govt.admin.common.util;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;

/**
 * @author
 */
@Slf4j
@Component
public class ApiTokenUtils {

    private final static String key = "877529a1b1f59c04a15b33ba41e487d7";

    // 一年过期(秒) 31622400L
    private final static Long expiration = 31622400L;

    /**
     * 创建新token
     *
     * @param userId 用户编号
     * @return token 令牌
     */
    public static String createToken(Long userId) {
        LocalDateTime nowDateTime = LocalDateTime.now();
        Instant instant = nowDateTime.toInstant(ZoneOffset.of("+8"));
        Date nowDate = Date.from(instant);

        String token = Jwts.builder().setSubject(userId.toString())
                .setIssuedAt(nowDate).setIssuer("KuMing NiGuang Science technology Co.")
                .setExpiration(getExpiration(nowDateTime))
                .signWith(SignatureAlgorithm.HS256, key).compact();
        log.debug("用户[" + userId + "]创建的token：" + token);
        return token;
    }

    /**
     * 令牌失效时间
     *
     * @param nowDateTime
     * @return
     */
    private static Date getExpiration(LocalDateTime nowDateTime) {
        log.debug("token生效时间：" + nowDateTime);
        Instant dateTime = nowDateTime.plusSeconds(expiration).toInstant(ZoneOffset.of("+8"));
        Date expirationDate = Date.from(dateTime);
        log.debug("token失效时间：" + expirationDate);
        return expirationDate;
    }


    /**
     * 通过令牌解析出userId
     *
     * @param token 令牌
     * @return userId 用户编号
     */
    public Long getUserIdByToken(String token) {
        return Long.valueOf(Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody().getSubject());
    }

    /**
     * 通过令牌解析出userId
     *
     * @return userId 用户编号
     */
    public Long getUserId() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        final String token = request.getHeader(HttpHeaders.AUTHORIZATION);
        log.debug("接收到token:" + token);
        if (StringUtils.isBlank(token)) {
            return null;
        }
        return getUserIdByToken(token);
    }


    public static void main(String[] args) {

        String newToken = createToken(1060806195251625985L);
        System.out.println("Authorization:" + newToken);

    }
}
